package com.jcfk.system.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.cache.redis.service.RedisStringService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.dao.SysDictionaryItemDao;
import com.jcfk.system.domain.dto.SysDictionaryDTO;
import com.jcfk.system.domain.dto.SysDictionaryItemDTO;
import com.jcfk.system.domain.dto.SysPermissionDTO;
import com.jcfk.system.domain.po.SysDictionary;
import com.jcfk.system.domain.po.SysDictionaryItem;
import com.jcfk.system.domain.query.SysDictionaryItemQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 字典数据项 服务
 */
@Slf4j
@Service
public class SysDictionaryItemService extends BaseService<SysDictionaryItemDao, SysDictionaryItem> {

    @Autowired
    private SysDictionaryService sysDictionaryService;

    /**
     * Redis 缓存键名
     */
    private static final String redisKeyName = "ServiceCache:SysDictionaryItem";

    @Autowired
    private RedisStringService redisStringService;

    /**
     * 根据条件获取分页列表
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysDictionaryItemDTO> queryByPage(DataPage<SysDictionaryItemDTO> page, SysDictionaryItemQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<SampleSimpleTableDTO>
     */
    public List<SysDictionaryItemDTO> getList(SysDictionaryItemQuery query) {
        QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysDictionary::getEnabled, 1);
        List<SysDictionary> sysDictionaries = sysDictionaryService.list(queryWrapper);

        // 查询条件
        QueryWrapper<SysDictionaryItem> qw = new QueryWrapper<>();
        if (!StrUtil.isEmpty(query.getDictionaryCode())) {
            qw.lambda().eq(SysDictionaryItem::getDictionaryCode, query.getDictionaryCode());
        }
        if (!StrUtil.isEmpty(query.getItemValue())) {
            qw.lambda().eq(SysDictionaryItem::getItemValue, Integer.parseInt(query.getItemValue()));
        }
        if (!StrUtil.isEmpty(query.getItemLabel())) {
            qw.lambda().like(SysDictionaryItem::getItemLabel, query.getItemLabel());
        }

        if (sysDictionaries.size() > 0) {
            List<String> codes = sysDictionaries.stream().map(SysDictionary::getCode).collect(Collectors.toList());
            qw.lambda().in(SysDictionaryItem::getDictionaryCode, codes);
        }

        qw.lambda().eq(SysDictionaryItem::getDeleted, 0);
        qw.lambda().eq(SysDictionaryItem::getEnabled, 1);

        qw.lambda().orderByAsc(SysDictionaryItem::getSort);
        // 查询数据
        List<SysDictionaryItem> list = super.list(qw);

        return convertList(list, SysDictionaryItemDTO.class);

    }

    /**
     * 根据主键获取单条数据
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysDictionaryItemDTO get(String id) {
        // 查询数据
        SysDictionaryItem item = this.baseMapper.selectById(id);
        SysDictionaryItemDTO dto = new SysDictionaryItemDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 插入对象
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysDictionaryItemDTO insert(SysDictionaryItemDTO dto) {
        // 默认数据
        this.setDefaultValue(dto);

        // 保存
        SysDictionaryItem item = new SysDictionaryItem();
        BeanUtils.copyProperties(dto, item);
        super.save(item);

        // 刷新缓存数据
        if (dto != null && StrUtil.isNotEmpty(dto.getDictionaryCode())) {
            this.refreshCache(dto.getDictionaryCode());
        }

        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 更新对象
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysDictionaryItemDTO update(SysDictionaryItemDTO dto) {
        // 默认数据
        this.setDefaultValue(dto);

        // 保存
        SysDictionaryItem item = new SysDictionaryItem();
        BeanUtils.copyProperties(dto, item);
        super.updateById(item);

        // 刷新缓存数据
        if (dto != null && StrUtil.isNotEmpty(dto.getDictionaryCode())) {
            this.refreshCache(dto.getDictionaryCode());
        }

        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 根据主键删除(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDelete(SysDictionaryItemDTO dto) {
        // 保存
        SysDictionaryItem item = this.baseMapper.selectById(dto.getId());

        if (item == null) return false;

        item.setDeleted(1);
        item.setVersion(dto.getVersion());
        int count = this.baseMapper.updateById(item);

        this.refreshCache(item.getDictionaryCode());

        return count >= 0 ? true : false;
    }

    /**
     * 根据主键删除(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysDictionaryItemDTO dto) {
        Boolean result = false;

        // 删除主表
        UpdateWrapper<SysDictionaryItem> uw = new UpdateWrapper<>();
        uw.lambda().in(SysDictionaryItem::getId, dto.getIds());
        uw.set("deleted", 1);
        this.update(uw);

        // 刷新缓存数据
        List<SysDictionaryDTO> sysDictionarys=sysDictionaryService.getList();
        for (SysDictionaryDTO dictionaryDTO : sysDictionarys) {
            this.refreshCache(dictionaryDTO.getCode());
        }

        result = true;
        return result;
    }

    /**
     * 设置添加默认值
     *
     * @param dto 添加对象
     */
    public void setDefaultValue(SysDictionaryItemDTO dto) {
        if (StrUtil.isEmpty(dto.getCreatedUserId())) {
            dto.setCreatedUserId(SecurityUtils.getUserId());
            dto.setCreateTime(new Date());
        }
        dto.setLastUpdatedUserId(SecurityUtils.getUserId());
        dto.setLastUpdateTime(new Date());
        dto.setDeleted(0);
    }

    /**
     * 校验合法性
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysDictionaryItemDTO dto) {

        QueryWrapper<SysDictionaryItem> qw = new QueryWrapper<>();
        if (!StrUtil.isEmpty(dto.getId())) {
            qw.lambda().ne(SysDictionaryItem::getId, dto.getId());
        }
        qw.lambda().eq(SysDictionaryItem::getDictionaryCode, dto.getDictionaryCode());
        qw.lambda().eq(SysDictionaryItem::getItemValue, dto.getItemValue());
        qw.lambda().eq(SysDictionaryItem::getDeleted, 0);

        Integer count = this.baseMapper.selectCount(qw);
        if (count > 0) {
            return RetResult.fail("当前字典下字典项值已存在");
        }

        return RetResult.ok();
    }

    /**
     * 刷新缓存
     *
     * @param dictionaryCode 字典编码
     * @return bool
     */
    public Boolean refreshCache(String dictionaryCode) {
        // 删除缓存
        redisStringService.delete(redisKeyName + ":" + dictionaryCode);

        // 刷新数据
        SysDictionaryItemQuery query = new SysDictionaryItemQuery();
        query.setDictionaryCode(dictionaryCode);
        List<SysDictionaryItemDTO> list = this.getList(query);
        redisStringService.setList(redisKeyName + ":" + dictionaryCode, list);

        return true;
    }

    /**
     * 根据 dictionaryCode 查询(缓存)
     *
     * @param dictionaryCode 字典编码
     * @return List<SysDictionaryInfo>
     */
    public List<SysDictionaryItemDTO> getListByCache(String dictionaryCode) {
        // 从缓存中获取
        List<SysDictionaryItemDTO> list = redisStringService.getList(redisKeyName + ":" + dictionaryCode, SysDictionaryItemDTO.class);

        if (ObjectUtil.isNull(list) || list.size() == 0) {
            // 从数据库中获取
            SysDictionaryItemQuery query = new SysDictionaryItemQuery();
            query.setDictionaryCode(dictionaryCode);
            list = this.getList(query);
            redisStringService.setList(redisKeyName + ":" + dictionaryCode, list);
        }

        // 排序
        list = list.stream().sorted(Comparator.comparing(SysDictionaryItemDTO::getSort)).collect(Collectors.toList());

        return list;
    }
}
